import router from '../router'
import store from '../store'
import * as events from '../store/events'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL, // url = base url + request url
  // 超时时间
  timeout: 20000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
})

service.defaults.withCredentials = true

// 配置axios
// service.defaults.transformRequest = [
//   function (data) {
//     let ret = ''
//     for (let it in data) {
//       if (Array.isArray(data[it])) {
//         data[it].forEach(item => {
//           ret += encodeURIComponent(it) + '=' + encodeURIComponent(item) + '&'
//         })
//       } else {
//         ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
//       }
//     }
//     return ret
//   }
// ]
// service.defaults.params = {
//   p: 'v'
// }

// 拦截response 事先统一处理
service.interceptors.response.use(
  function (response) {
    // Do something with response data
    if (Number(response.data.status) === 1) {
      return response
    } else if (Number(response.data.status) === 10000) {
      Cookies.remove('czt_openinfo', {
        path: '/',
        domain: process.env.VUE_APP_COOKIE_DOMAIN,
      })
      store.commit(events.CHANGE_USER_INFO, {})
      router.push('/login')
      window.sessionStorage.removeItem('WXAUTH')
      return Promise.reject({
        msg: response.data.msg,
        data: response.data,
      })
    } else {
      return Promise.reject({
        msg: response.data.msg,
        data: response.data,
      })
    }
    return response
  },
  function (error) {
    // Do something with response error
    return Promise.reject({
      msg: '网络错误',
      err: error,
    })
  }
)
// 把axios放到全局中
Vue.prototype.$http = service

export default service